package com.inspur.ydt.util;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.inspur.iop.OpenApi;
import com.inspur.iop.model.IopException;
import com.inspur.iop.model.PostParameter;
import com.inspur.ydt.openapi.OpenApiProvider;

public class RequestUtils {

	
	private static OpenApiProvider provider;
	@Autowired
	public RequestUtils(OpenApiProvider provider) {
		RequestUtils.provider = provider;
	}
	

	
	//公共参数数量
	private static final int COMMON_PARAMETER_NUMBER = 2;
	
	/**
	 * 生成请求参数 数组
	 * @param strings
	 * @return
	 */
	public static PostParameter[] generatePostParameters(String...strings) {
		int stringsLength = strings.length;
		//键值对数量，成对传入
		int keyValuePairNumber = stringsLength / 2;
		PostParameter[] postparams = new PostParameter[COMMON_PARAMETER_NUMBER + keyValuePairNumber]; 
		//说明是客户端的请求
		setCommonParameters(postparams);
		for (int i = 0; i < keyValuePairNumber; i++) {
			postparams[i + COMMON_PARAMETER_NUMBER] = new PostParameter(strings[2 * i], strings[2 * i + 1]);

		}
		return postparams;
	}
	
	/**
	 * 生成请求参数 数组
	 * @param parametersMap
	 * @return
	 */
	public static PostParameter[] generatePostParameters(Map<String, String> parametersMap) {
		//键值对数量
		int keyValuePairNumber = parametersMap.size();
		PostParameter[] postparams = new PostParameter[COMMON_PARAMETER_NUMBER + keyValuePairNumber]; 
		//说明是客户端的请求
		setCommonParameters(postparams);
		int index = COMMON_PARAMETER_NUMBER;
		for (Map.Entry<String, String> entry : parametersMap.entrySet()) {
			postparams[index++] = new PostParameter(entry.getKey(), entry.getValue());
		}
		return postparams;
	}
	
	/**
	 * 设置公共的请求参数
	 * @param postparams
	 */
	private static void setCommonParameters(PostParameter[] postparams) {
		// 说明是客户端的请求
		postparams[0] = new PostParameter("grant_type", "client_credentials");
		postparams[1] = new PostParameter("method", "client");
	}
	
	/**
	 * 
	 * @param url
	 * @param version
	 * @param postparams
	 * @return
	 */
	public static String requestInfo(String url, String version, PostParameter[] postparams) {
		OpenApi api = provider.getConnection();
		String result = null;
		try {
			result = api.getResponse(url, version, "post", postparams).toString();
		} catch (IopException e) {
			result = "请求异常";
			e.printStackTrace();
		}
		System.out.println(result);
		return result;
	}
}
